iT邦幫忙

2024 iThome 鐵人賽

DAY 2
0

Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).

Specifically, ans is the concatenation of two nums arrays.

Return the array ans.


題目可以說是一點都看不懂啊!
翻譯之後雖然還是覺得很繞,但看到範例時就恍然大悟了...

  • index =索引
  • concatenation =拼接
    簡單來說就是把nums重複兩次拼接成新的陣列ans!
    https://ithelp.ithome.com.tw/upload/images/20240916/20169432xrHOgl4vuS.jpg
    馬上直覺聯想到了for迴圈~

很順利的寫出來了,甚至覺得有一點小簡單!

public class Solution {
public int[] getConcatenation(int[] nums){
//建立一個可以存放兩倍n長度的矩陣
int[] ans = new int[2*nums.length];

    //複製nums的值到ans兩次
    for (int i = 0; i < nums.length; i++){
        //第一次
        ans[i] = nums[i];
        //第二次
        ans[i+nums.length] =nums[i];
    }
    return ans;
}

}
馬上丟去leetcode看看~
https://ithelp.ithome.com.tw/upload/images/20240916/20169432Zxm3aibEmI.png
成功啦啦啦:P


一樣去看看別人寫的正確答案,結果發現跟我寫的差不多
唯一的差距是他

  • 宣告了一個len=nums.length,寫程式時會比較方便。

class Solution {
public int[] getConcatenation(int[] nums) {
int len = nums.length;
int[] ans = new int[2*len];
for(int i = 0; i < len; i++){
ans[i] = nums[i];
ans[i+len] = nums[i];
}
return ans;
}
}


總覺得今天題目的難度比昨天低了不少,一定是烤肉之神的眷顧吧!!
最後預祝看到這裡的你中秋佳節愉快!


上一篇
day-1 [easy.1694]reformat phone number
下一篇
day-3[easy.2047]number of valid words in a sentence
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言